iT邦幫忙

2024 iThome 鐵人賽

DAY 1
0

234. Palindrome Linked List

題目敘述:

given the head of a singly linked list, return true if it is a palindromeor false otherwise.
Example 1:
https://ithelp.ithome.com.tw/upload/images/20240128/20162696vbJUhZBqbd.png
Input: head = [1,2,2,1]
Output: true
Example 2:
https://ithelp.ithome.com.tw/upload/images/20240128/20162696wAxhnjgwUR.png
Input: head = [1,2]
Output: false

程式碼(C++):

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *slow = head, *fast = head, *prev, *temp;
        while(fast && fast->next)
            slow = slow->next, fast = fast->next->next;
        prev = slow, slow = slow->next, prev->next = NULL;
        while(slow)
            temp = slow->next, slow->next = prev,prev = slow, slow = temp;
        fast = head, slow = prev;
        while(slow)
            if(fast->val != slow->val) return false;
            else fast = fast ->next, slow = slow -> next;
        return true;
    }
};

系列文
Leetcode 解題之旅:逐日攻克1
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言